package com.watson.todolist;

import java.security.GeneralSecurityException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.watson.todolist.constants.DatabaseConstants;
import com.watson.todolist.constants.TodoListConstants;
import com.watson.todolist.database.AccountManager;
import com.watson.todolist.database.DatabaseManager;
import com.watson.todolist.database.TagManager;
import com.watson.todolist.database.ToDoListManager;
import com.watson.todolist.to.TagItem;
import com.watson.todolist.to.TodoItem;
import com.watson.todolist.to.TodoListAccount;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This is the main page for the ToDoList Manager App. It consists of the user
 * login page and buttons to go the other pages after either login, register, or
 * forgotten passsword actions.
 * 
 * @author Jasmin Muminhodzic
 * @version 1.0
 * 
 */
public class mainLoginPage extends Activity {

	AccountManager accountManager;
	Button logIn;
	Button forgotPassword;
	Button register;
	EditText username;
	EditText password;

	/**
	 * This method is called when the activity is created.
	 * 
	 * @param savedInstanceState
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);

		accountManager = new AccountManager(new DatabaseManager().open(this));

		logIn = (Button) findViewById(R.id.buttonLogin);
		forgotPassword = (Button) findViewById(R.id.forgotPasswordButton);
		register = (Button) findViewById(R.id.createAccountButton);

		logIn.setOnClickListener(onLoginPageClickListener);
		forgotPassword.setOnClickListener(onForgetPageClickListener);
		register.setOnClickListener(onRegisterPageClickListener);

		username = (EditText) findViewById(R.id.userName);
		password = (EditText) findViewById(R.id.userPassword);

		// TESTING
		//boolean deleted = deleteDatabase(DatabaseConstants.DB_NAME);
		/*
		 * try { testTodoListTable(); } catch (ParseException e) {
		 * e.printStackTrace(); } testTagsTable();
		 */
	}

	/**
	 * This functions as the listener object for the LoginButton. Checks the
	 * login data and if username and pasword are correct, proceeds to the next
	 * screen.
	 */
	private OnClickListener onLoginPageClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// successful login
			boolean loginCheck = false;

			try {
				loginCheck = accountManager.authenticateUserAccount(username
						.getText().toString(), password.getText().toString());
			} catch (GeneralSecurityException e) {
				Toast.makeText(getApplicationContext(), "Login failed", 4000)
						.show();
			}

			if (loginCheck) {
				DatabaseManager dbManager = new DatabaseManager();
				SQLiteDatabase db = dbManager.open(getApplicationContext());
				AccountManager accountManager = new AccountManager(db);

				// Get user account in AccountManager from the database
				Cursor cursor = accountManager
						.getUserAccountByUserName(username.getText().toString());

				if (cursor != null && cursor.getCount() != 0) {
					String email = cursor
							.getString(cursor
									.getColumnIndex(DatabaseConstants.ACCOUNT_TABLE_EMAIL_ADDRESS));
					long userId = cursor.getLong(cursor
							.getColumnIndex(DatabaseConstants.ID));

					// Fill TodoListAccount instance with user information
					TodoListAccount account = TodoListAccount.getInstance();
					account.setEmailAddress(email);
					account.setUserId(userId);
					account.setUserName(username.getText().toString());

					// Close database
					dbManager.close();

					Intent myIntent = new Intent(v.getContext(),
							todoListActivity.class);
					startActivityForResult(myIntent, 3);
				} else {
					// display error message to User using a custom "toast"
					// message
					LayoutInflater inflater = getLayoutInflater();
					View toastLayout = inflater.inflate(R.layout.custom_toast,
							(ViewGroup) findViewById(R.id.custom_toast_root));
					// setting image of custom toast message
					((ImageView) toastLayout.findViewById(R.id.toastImg))
							.setImageResource(R.drawable.error_img);
					// setting text of custom toast message
					((TextView) toastLayout.findViewById(R.id.toastText))
							.setText("ERROR: Incorect username and/or password");

					Toast loginError = Toast.makeText(getApplicationContext(),
							"", 4000);
					loginError.setView(toastLayout);
					loginError.show();
				}

			}
			// unsuccessful login
			else {
				// display error message to User using a custom "toast" message
				LayoutInflater inflater = getLayoutInflater();
				View toastLayout = inflater.inflate(R.layout.custom_toast,
						(ViewGroup) findViewById(R.id.custom_toast_root));
				// setting image of custom toast message
				((ImageView) toastLayout.findViewById(R.id.toastImg))
						.setImageResource(R.drawable.error_img);
				// setting text of custom toast message
				((TextView) toastLayout.findViewById(R.id.toastText))
						.setText("ERROR: Incorect username and/or password");

				Toast loginError = Toast.makeText(getApplicationContext(), "",
						4000);
				loginError.setView(toastLayout);
				loginError.show();

			}
		}
	};

	/**
	 * this functions to get the forgotten password activity as the current
	 * screen
	 */
	private OnClickListener onForgetPageClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent myIntent = new Intent(v.getContext(),
					forgotPasswordPage.class);
			startActivity(myIntent);
		}
	};

	/**
	 * this functions to get the registration page activity as the current
	 * screen
	 */
	private OnClickListener onRegisterPageClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent myIntent = new Intent(v.getContext(), registrationPage.class);
			startActivityForResult(myIntent, 1);
		}
	};

}
